package com.besall.allbase.view.activity.tools.FileActivity;

/**
 * @author ericshen
 * @time $ $
 */

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import bb.lanxing.R;

import com.besall.allbase.common.Constants;
import com.besall.allbase.common.utils.LogUtils;
import com.besall.allbase.common.utils.SlideLayout;
import com.besall.allbase.view.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

//import static com.besall.allbase.common.Constants.CHIPS_FILE_PATH_RESULT;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;


public class LogFilelistActivity extends BaseActivity<IFilelistActivity, FilelistPresenter> implements IFilelistActivity,AdapterView.OnItemClickListener {
    private static final String TAG = "FilelistActivity";
    private static LogFilelistActivity instance;
    private ListView mListView;
    private MyFileAdapter mAdapter;
    private LogFilelistActivity mContext;
    private File currentFile;
    String sdRootPath;
    public String cur_title = "FILES";
    private ArrayList<FileEntity> mList;
    private Set<SlideLayout> sets = new HashSet();
    private Handler mHandler;



    @Override
    protected FilelistPresenter createPresenter() {

        return new FilelistPresenter();
    }

    @Override
    protected void initBeforeSetContent() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.file_list;
    }

    @Override
    protected void bindView() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        if (mAdapter == null) {
                            Log.i(TAG, "handleMessage: -111");
                            mAdapter = new MyFileAdapter(mContext, mList);
                            mListView.setAdapter(mAdapter);
                            Log.i(TAG, "handleMessage: mListView-" +mListView);;
                        } else {
                            Log.i(TAG, "handleMessage: -2222");;
                            mAdapter.notifyDataSetChanged();
                        }

                        break;
                    case 2:

                        break;

                    default:
                        break;
                }
            }
        };
        mListView = (ListView) findViewById(R.id.filename);
        mContext = this;
        mList = new ArrayList<>();
//        sdRootPath = getFolderPath()+"Android/" + "data/" + "com.bes.besall/" + "files/";
        currentFile = getExternalFilesDir("LogDump");
        System.out.println(sdRootPath);
        initView();
        getData(sdRootPath);
    }

    public void initView() {
        inittoolbar(cur_title);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "onItemClick: +1");
                final FileEntity entity = mList.get(position);
                if (entity.getFileType() == FileEntity.Type.FLODER) {
                    Log.i(TAG, "onItemClick: +++floder");
                    currentFile = new File(entity.getFilePath());
                    getData(entity.getFilePath());
                } else if (entity.getFileType() == FileEntity.Type.FILE) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Log.i(TAG, "onItemClick: +++file");
                            Intent intent = new Intent();
                            intent.putExtra("getFilePath",entity.getFilePath());
                            intent.putExtra("getFileName",entity.getFileName());

                            Log.i(TAG, "getFilePath: " + entity.getFilePath());
                            Log.i(TAG, "getFileName: " + entity.getFileName());
                            setResult(Constants.CHIPS_FILE_PATH_RESULT, intent);
                            finish();
                            showToast(entity.getFilePath());
//                            AudioDumpPresenter.player(entity.getFilePath(),0);
                           
                            //Toast.makeText(mContext, entity.getFilePath() + "  " + entity.getFileName(),1).show();
                        }
                    });
                }

            }
        });
    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    private void getData(final String path) {
        new Thread() {
            @Override
            public void run() {
                super.run();

                findAllFiles();
            }
        }.start();

    }


    /**
     * 查找path地址下所有文件
     *
//     * @param path
     */
    public void findAllFiles() {
        mList.clear();

//        if (path == null || path.equals("")) {
//            return;
//        }
        File fatherFile = getExternalFilesDir("LogDump");
        File[] files = fatherFile.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                FileEntity entity = new FileEntity();
                boolean isDirectory = files[i].isDirectory();
                if (isDirectory == true) {
                    entity.setFileType(FileEntity.Type.FLODER);
//					entity.setFileName(files[i].getPath());
                } else {
                    entity.setFileType(FileEntity.Type.FILE);
                }
                entity.setFileName(files[i].getName().toString());
                entity.setFilePath(files[i].getAbsolutePath());
                entity.setFileSize(files[i].length() + "");
                mList.add(entity);
            }
        }
        mHandler.sendEmptyMessage(1);

    }



    class MyFileAdapter extends BaseAdapter {
        private Context mContext;
        private ArrayList<FileEntity> mAList;
        private LayoutInflater mInflater;


        public MyFileAdapter(LogFilelistActivity mContext, ArrayList<FileEntity> mList) {
            super();
            this.mContext = mContext;
            this.mAList = mList;
            mInflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mAList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return mAList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            if (mAList.get(position).getFileType() == FileEntity.Type.FLODER) {
                return 0;
            } else {
                return 1;
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        public ArrayList<FileEntity> findAllFolderFiles(String path) {
            ArrayList<FileEntity> folderlist = new ArrayList<>();
            folderlist.clear();
            if (path == null || path.equals("")) {
                return folderlist;
            }
            File fatherFile = new File(path);
            File[] files = fatherFile.listFiles();
            if (files != null && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    FileEntity entity = new FileEntity();
                    boolean isDirectory = files[i].isDirectory();
                    if (isDirectory == true) {
                        entity.setFileType(FileEntity.Type.FLODER);
                    } else {
                        entity.setFileType(FileEntity.Type.FILE);
                    }
                    entity.setFileName(files[i].getName().toString());
                    entity.setFilePath(files[i].getAbsolutePath());
                    entity.setFileSize(files[i].length() + "");
                    folderlist.add(entity);
                }
            }
            return  folderlist;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

//			System.out.println("position-->"+position+"    ---convertView--"+convertView);
            ViewHolder holder = null;
            int type = getItemViewType(position);
            FileEntity entity = mAList.get(position);

            if (convertView == null) {
                holder = new ViewHolder();
                switch (type) {
                    case 0://folder
                        convertView = mInflater.inflate(R.layout.item_file_list, parent, false);
                        holder.Content =(View) convertView.findViewById(R.id.content);
                        holder.iv = (ImageView) convertView.findViewById(R.id.item_imageview);
                        holder.tv = (TextView) convertView.findViewById(R.id.file_name);
                        holder.dv = (TextView) convertView.findViewById(R.id.delete_button);
                        break;
                    case 1://file
                        convertView = mInflater.inflate(R.layout.item_file_list, parent, false);
                        holder.Content =(View) convertView.findViewById(R.id.content);
                        holder.iv = (ImageView) convertView.findViewById(R.id.item_imageview);
                        holder.tv = (TextView) convertView.findViewById(R.id.file_name);
                        holder.dv = (TextView) convertView.findViewById(R.id.delete_button);

                        break;

                    default:
                        break;

                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.Content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG, "onItemClick: +1");
                    final FileEntity entity = mList.get(position);
                    if (entity.getFileType() == FileEntity.Type.FLODER) {
                        Log.i(TAG, "onItemClick: +++floder");
                        currentFile = new File(entity.getFilePath());
                        getData(entity.getFilePath());
                    } else if (entity.getFileType() == FileEntity.Type.FILE) {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Log.i(TAG, "onItemClick: +++file");
                                Intent intent = new Intent();
                                intent.putExtra("getFilePath", entity.getFilePath());
                                intent.putExtra("getFileName", entity.getFileName());
//                                intent.putExtra("getFileName", entity.getFileName());
                                Log.i(TAG, "getFilePath: " + entity.getFilePath());
                                Log.i(TAG, "getFileName: " + entity.getFileName());
                                setResult(Constants.CHIPS_FILE_PATH_RESULT, intent);
                                finish();
                                showToast(entity.getFilePath());

//                            AudioDumpPresenter.player(entity.getFilePath(),0);
//
                                //Toast.makeText(mContext, entity.getFilePath() + "  " + entity.getFileName(),1).show();
                            }
                        });
                    }
                }
            });

            holder.dv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SlideLayout slideLayout = (SlideLayout) v.getParent();
                    slideLayout.closeMenu();
                    File file = new File(entity.getFilePath());
                    Log.i(TAG, "onClick: delete" + entity.getFilePath());
                    Log.i(TAG, "onClick: ---"+ type);
                    if(type == 0) {
                        Log.i(TAG, "onClick: type 0 " );
                        ArrayList<FileEntity> folderlist = findAllFolderFiles(entity.getFilePath());
                        Log.i(TAG, "onClick:--------" + folderlist.size());
                        for(int i = 0; i < folderlist.size(); i ++) {
                            FileEntity delete = folderlist.get(i);
                            String path = delete.getFilePath();
                            File folderfiles = new File(path);
                            if (folderfiles.exists())
                            folderfiles.delete();
                        }
                    }
                    if (file.exists())
                    file.delete();
                    mList.remove(entity);
                    notifyDataSetChanged();
                }
            });


            switch (type) {
                case 0:
                    holder.iv.setImageResource(R.drawable.ic_documents);
                    holder.tv.setText(entity.getFilePath());
                    break;
                case 1:
                    holder.iv.setImageResource(R.drawable.ic_file);
                    holder.tv.setText(entity.getFilePath());
                    break;

                default:
                    break;
            }

            SlideLayout slideLayout = (SlideLayout) convertView;
            slideLayout.setOnStateChangeListener(new MyOnStateChangeListener());

            return convertView;
        }

    }

    class ViewHolder {
        View Content;
        ImageView iv;
        TextView tv;
        TextView dv;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == android.R.id.home){
            this.finish();
        }

/*        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
        }*/
        return super.onOptionsItemSelected(item);
    }



    protected void LOG(String msg){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            LogUtils.e_write(TAG ,msg+"");
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    public SlideLayout slideLayout = null;
    class MyOnStateChangeListener implements SlideLayout.OnStateChangeListener
    {
        /**
         * 滑动后每次手势抬起保证只有一个item是open状态，加入sets集合中
         **/
        @Override
        public void onOpen(SlideLayout layout) {
            slideLayout = layout;
            if (sets.size() > 0) {
                for (SlideLayout s : sets) {
                    s.closeMenu();
                    sets.remove(s);
                }
            }
            sets.add(layout);
        }

        @Override
        public void onMove(SlideLayout layout) {
            if (slideLayout != null && slideLayout !=layout)
            {
                slideLayout.closeMenu();
            }
        }

        @Override
        public void onClose(SlideLayout layout) {
            if (sets.size() > 0) {
                sets.remove(layout);
            }
            if(slideLayout ==layout){
                slideLayout = null;
            }
        }

    }


}




